package com.wwwc.index.web.filters;

import java.io.*;
import java.sql.Timestamp;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

import com.wwwc.index.web.ejb.database.*;
//import com.wwwc.index.web.database.*;

public final class IndexFilter implements Filter {
    private EJBDatabaseQuery ejbdb;
    private FilterConfig filterConfig = null;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }
    
    public void destroy() {
        this.filterConfig = null;
    }
 
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
	throws IOException, ServletException {

	String user_ip   = request.getRemoteAddr();

	if (filterConfig == null) {
	    return;
	}

	if (ejbdb == null) {
	    ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	}
	
	if(user_ip == null || user_ip.length() <10 ||user_ip.length()>15) {
	    return;
	}

	String query ="SELECT * FROM BLOCKED_IPS WHERE USER_IP='"+user_ip+"' ORDER BY TIMESTAMP DESC;";
	Hashtable iphs = ejbdb.selectSingleRecordHashtable(query);

	if(iphs == null || iphs.isEmpty()) {
	    chain.doFilter(request, response);	
	    //System.out.print("Do Filter............OK");
	    return;
	}

	String time = ""+iphs.get("TIME");
	String block_time = ""+iphs.get("FIELD9");

	if((System.currentTimeMillis()-Long.parseLong(time)) > Long.parseLong(block_time)) {
	    chain.doFilter(request, response);
	    System.out.println("Filter........released["+user_ip+"]");
	    query ="DELETE FROM BLOCKED_IPS WHERE USER_IP='"+user_ip+"';";
	    ejbdb.delete(query);
	    return;
	}

	PrintWriter out = response.getWriter();
	out.println("<HTML><HEAD>");
	out.println("<TITLE>Blocked IP</TITLE>");
	out.println("</HEAD>");
	out.println("<SCRIPT>");
	out.println("function ChangeUrl() {");

	if(user_ip.startsWith("192.168.1.10")) {
	    out.println("    if (top.location !=\"http://192.168.1.103/Blocked.html\") {");
	    out.println("      top.location.replace(\"http://192.168.1.103/Blocked.html\");");
	}
	else {
	    out.println("    if (top.location !=\"http://www.3wcnter.com/Blocked.html\") {");
	    out.println("      top.location.replace(\"http://www.3wcenter.com/Blocked.html\");");
	}

	out.println("      return true;");
	out.println("    }");
	out.println("}");
	out.println("</SCRIPT>");
	out.println("<BODY onLoad=ChangeUrl();>");
	out.println("</BODY></HTML>");

	System.out.println("==========================Blocked!===============================");
	System.out.println("[IP ID="+iphs.get("FIELD1")+"][USER IP="+user_ip+"][TIMESTAMP="+iphs.get("TIMESTAMP")+"]");
	System.out.println("[DURATION="+iphs.get("FIELD9")+"][BLOCKED_BY="+iphs.get("BLOCKED_BY")+"]");
	System.out.println("[USERNAME="+iphs.get("USERNAME")+"][TARGET_PAGE="+iphs.get("TARGET_PAGE")+"]");
	System.out.println("[POLICY="+iphs.get("POLICY")+"][FIELD10="+iphs.get("FIELD10")+"]");
	return;
    }
}
